package cn.edu.sdjzu.xg.bysj.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Desc:properties文件获取工具类
 */
public class PropertyUtil {
    private static final Logger log = LogManager.getLogger(PropertyUtil.class);
    private static Properties props;
    static{
        loadProps();
    }
    //加载properties文件
    synchronized static private void loadProps(){
        log.info("开始加载properties文件内容.......");
        props = new Properties();
        InputStream in = null;
        try {
            //第一种，通过类加载器进行获取properties文件流-
            in = PropertyUtil.class.getClassLoader().getResourceAsStream("bysj.properties");
            //第二种，通过类进行获取properties文件流-->
            //in = PropertyUtil.class.getResourceAsStream("/bysj.properties");
            props.load(in);

        } catch (FileNotFoundException e) {
            log.error("bysj.properties文件未找到");
        } catch (IOException e) {
            log.error("出现IOException");
        } finally {
            try {
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("bysj.properties文件流关闭出现异常");
            }
        }
        log.info("加载properties文件内容完成...........");
        log.info("properties文件内容：" + props);
    }
    //根据属性名返回属性值
    public static String getProperty(String key){
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }
    //根据属性名返回属性值，如果没有指定属性，则返回默认值
    public static String getProperty(String key, String defaultValue) {
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }

    public static void main(String[] args) {
        log.debug(PropertyUtil.getProperty("jdbc.driver"));
        log.debug(PropertyUtil.getProperty("jdbc.username"));
        log.debug(PropertyUtil.getProperty("jdbc.password"));
        log.debug(PropertyUtil.getProperty("jdbc.password1","alli"));
    }
}
